<?php
namespace app\admin\controller;

use app\admin\library\AdminController;
use app\admin\library\User;
use app\admin\library\Upload;
use cubox\Cubox;

class File extends AdminController{
    public function onUpload(){
        if (empty($_FILES['file'])){
            exit('参数错误');
        }

        $file = $_FILES['file'];
        $cate = 'test';
        $filename =  $this->getFileName($file['name'],1);
        $filetype = pathinfo($file['name'], PATHINFO_EXTENSION);
        $info['title'] = pathinfo($file['name'], PATHINFO_FILENAME);
        $info['size'] = $file['size'];

        $config = Cubox::config('upload');

        if ($config->disabled){
            throw new \Exception('上传功能已关闭');
        }

        //size
        $unit  = $config->file_size_unit??'MB';
        $size  = $config->file_size??10;
        $unitSize = 1024*1024;

        if ($unit == 'KB'){
            $unitSize  = 1024;
        }

        $type  = $config->file_type??[];

        if (!in_array($filetype,$type) || $filetype=='') {
            throw new \Exception('文件类型错误');
        }

        if ($file['size'] > $size * $unitSize){
            throw new \Exception('文件大小超过限制 {$size}{$unit}');
        }

        $folder = date($config->folder_type??'/YYYYMM/DD/',time());

        $move_path = ROOT.DS.UPLOAD.DS.$folder;

        if (file_exists($move_path) || mkdir($move_path,0777,true)){

            if ($file['error'] == UPLOAD_ERR_OK) {
               if (move_uploaded_file($file['tmp_name'],$move_path.DS.$filename)){

                    $url = '/'.$folder.'/'.$filename;
                    if ($this->fileLog($cate,$url,$info)){
                        return array('url'=>$url);
                    }else{
                        throw new \Exception('上传失败 未能移动文件到DATA');
                    }

               }else{
                    throw new \Exception('上传失败 未能移动文件到UPLOAD');
               }

            }else{
                throw new \Exception('上传失败 '.$file['error']);
            }
        
        }else{
            throw new \Exception('UPLOAD目录不能创建文件夹');
        }
    }

    private function getFileName($name,$index){
        $ext =   pathinfo($name, PATHINFO_EXTENSION);
        return time().rand(100000,9999999).$index.'.'.$ext;
       // print_r($arr);
    }

    public function onInfo(){
        $file = $this->post('file',$this->check('文件')->required());

        $fileLog = $this->model('UserFileLog');
  
        $data = $fileLog->where('file','in',$file)->getData();

        foreach($data as $key => $value){
            $data[$key]['date'] = date('Y-m-d H:i:s',$value['time']);
        }

        return $data;
    }

    public function onConfig(){
        $config = Cubox::config('upload');

        $re['disabled']  = $config->disabled??false;
         //size
        $unit  = $config->file_size_unit??'MB';
        $size  = $config->file_size??10;
        $unitSize = 1024*1024;

        if ($unit == 'KB'){
            $unitSize  = 1024;
        }

        $re['type'] = array_filter($config->file_type??[],function($value){
            return $value!='';
        });


        $re['size'] = $size*$unitSize;

        return $re;
    }

    public function onDialogList(){

        $time = $this->post('time');
        $keyword  = $this->post('keyword');
        $pageCurrent = $this->post('page',$this->check('页码')->type('int')->default(1));
        $user_id = User::get('user_id');
        $ext =  $this->post('ext');
        
        $file = $this->model('UserFileLog');

        $file->where('user_id',$user_id);

        if ($time){
            switch($time){
                case "today":
                //查询今天的数据
                    $file->where('time','>=',time()-86400);
                    break;
                case "yesterday":
                    //查询昨天的数据
                    $file->where('time','>=',time()-86400*2);
                    break;
                case "week":
                    //查询本周的数据
                    $file->where('time','>=',time()-86400*7);
                    break;
                case "month":
                    //查询本月的数据
                    $file->where('time','>=',time()-86400*30);
                break;
            }
        }


        if ($keyword){
            $file->where(['title'],'LIKE','%'.trim($keyword).'%');
        }
        
        if ($ext){
            if (is_string($ext) ) $ext = explode(',',$ext);
            $file->where('ext','in',$ext);
        }
       
        $list = $file->page($pageCurrent,20)->order('time','DESC')->getData();
        
        foreach($list as $key => $value){
            $list[$key]['date'] = date('Y-m-d H:i:s',$value['time']);
            //$list[$key]['file'] = Upload::url($value['file']);
        }


        return ['list' => $list,'total'=>$file->total,'count'=>$file->pageCount];
    }


    public function onSystemFile(){
        $type = $this->post('type',$this->check('类型')->required());
        $path = str_replace('/',DS,$this->post('path',$this->check('路径')->required()));
        $ext  = $this->post('ext',$this->check('文件类型')->required());
        $system  = $this->post('system',$this->check('系统')->type('bool')->default(false));

        $path  = $path==DS?ROOT:ROOT.$path;

        if (!$system && $this->isProtectPath($path)){
            throw new \Exception('禁止访问系统文件');
        }


        if (!is_dir($path)){
            throw new \Exception('路径不存在');
        }


        $list = scandir($path);

        $filelist = [];
        $folderList = [];


        foreach( $list as $value){
            if ($value== '.' || $value== '..') continue;

            if (is_file($path.DS.$value)){
                $fileExt = pathinfo($value, PATHINFO_EXTENSION);
                if ($ext=='*' || $fileExt == $ext){
                    $filelist[] = [
                        'type' => 'file',
                        'name' => $value,
                    ];
                }
            }else{
                if ($system || !$this->isProtectPath($path.DS.$value)){
                    $folderList[] = [
                        'type' => 'folder',
                        'name' => $value,
                    ];
                }
            }
        }


        $re = [];

        if ($type=='all' || $type=='file'){
            $re = array_merge($folderList,$filelist);
        }else{
            $re = $folderList;
        }
        
        return $re;
    }

    //被保护的系统文件路径
    private function isProtectPath($path){
         
        
        $pathList[] = ROOT.DS.CUBOX;
        $pathList[] = ROOT.DS.APP;
        $pathList[] = ROOT.DS.CONFIG;
        $pathList[] = ROOT.DS.RUNTIME;

        foreach($pathList as $key => $value){
            if (strpos($path,$value) === 0){
                return true;
            }
        }

        return false;
    }


    public function onIndex(){
        $this->pageTitle = '文件管理';
        $this->pageIcon = 'fa-file';
        return $this->display();
    }

}